﻿using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace enterprise.Website.Core.Filter
{
    /// <summary>
    /// 外部接口验证
    /// </summary>
    public class ApiAuthorizeAttribute : ActionFilterAttribute
    {
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string Token = context.HttpContext.Request.Headers["Token"].ToString();
            if (Token.IsNullOrWhiteSpace())
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
                context.HttpContext.Response.ContentType = "application/json;charset=UTF-8";
                await context.HttpContext.Response.WriteAsync(new ApiResult
                {
                    Success = false,
                    Message = "请传入Token",
                    StatusCode = (int)HttpStatusCode.Unauthorized
                }.ToJson());
                return;
            }
            var isPass = await ApiLogin.TokenLogin(Token,string.Empty, context.HttpContext.Request.Host.Host);
            if (isPass)
            {
                await base.OnActionExecutionAsync(context, next);
            }
            else
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
                context.HttpContext.Response.ContentType = "application/json;charset=UTF-8";
                await context.HttpContext.Response.WriteAsync(new ApiResult
                {
                    Success = false,
                    Message = "Token验证不通过",
                    StatusCode = (int)HttpStatusCode.Unauthorized
                }.ToJson());
                return;
            }
        }
    }
}
